<?php

namespace app\admin\controller;
use think\Db;
use think\Request;

class Classify extends Admin
{

    public function __construct(){
        parent::initialize();
        // var_dump($this->initialize()) ;

    }
	//分类详情
    public function classify($table,$name)
    {
    	$list = Db::name($table)->where('parent_id',0)->field(['name', 'id'])->select();
        return $this->fetch('classify\classify',[
        			'list' => $list,
                    'name' => $name,
                    'table'=> $table
        	]);        
    }

    //子分类
    public function subcategory(Request $request)
    {	

    	$id=$_POST['id'];
        // $id = 1;
        $table = $_POST['table'];
        // $table = 'tb_music_classify';
    	$list = Db::name($table)->where('parent_id',$id)->select();
      
    	echo json_encode($list);
    }
    //添加分类显示页面
    public function addclassify(Request $request){

       
        $table = $_POST['table'];
        $name = $_POST['name'];
    	return $this->fetch('addclassify/addclassify',[
                        'table'=>$table,
                        'name' =>$name
        ]);
    }



    //添加一级分类
    public function add(Request $request){
    	$data = Request::instance()->post();
    	 // var_dump($data);

    	if ($data['parent_id'] == 0) {    		
    	$result=Db::table($data['table'])
    			->data(['name'=>$data['name'],'parent_id'=>$data['parent_id']])
    			->insert();
    	}
    	if ($result) {
            return $this->success('添加成功!',url('classify/classify',['table'=>$data['table'],'name'=>$data['listname']]));
    	}
    }

    //删除一级分类
    public function del(Request $request)
    {
    	$data = Request::instance()->post();
    	// var_dump($data);
    	$list = Db::name($data['table'])->where('parent_id',$data['id'])->select();
    	if ($list) {
    		return $this->error('请先删除子分类');
    	} else {

    		$result = Db::table($data['table'])->where('id',$data['id'])->delete();
    		if ($result) {
    			return $this->success('删除成功');
    		}
    	}

    }

    // 添加子分类
    public function addsubcategory(Request $request)
    {
    	$data = Request::instance()->post();
        $table = $data['table'];
    	$result=Db::table($table)
    			->data(['name'=>$data['name'],'parent_id'=>$data['parent_id']])
    			->insert();
    	// $list = Db::name('tb_classify')->insert();
    	echo json_encode($result);
    	// return $this->fetch('addsubcategory/addsubcategory');
    }

    //删除子分类
    public function delsubcategory(Request $request)
    {
    	$id = $_POST['id'];
        $table = $_POST['table'];
    	$result = Db::table($table)->where('id',$id)->delete();
    	echo json_encode($result);
    }

}
